
import json
from update import downland_remote_files, UpdateWebSocketClient
import paho.mqtt.client as mqtt
from setting import logger, NS_HOST

# 连接成功回调
def on_connect(client, userdata, flags, rc):
    print('Connected with result code '+str(rc))
    client.subscribe('lora1')

# 消息接收回调
def on_message(client, userdata, msg):

    print(msg.topic+" "+str(msg.payload))

    print(json.loads(msg.payload.decode()))

    parse_msg = json.loads(msg.payload.decode())

    task_type = parse_msg["task_type"]

    if task_type == "Sensor upgrade": # 传感器升级  
        '''
        
        {
            "task_type": "Sensor upgrade",
            "data": {
                "file_url": "http://192.168.88.34:33332/platform-tools_r34.0.3-windows.zip",
                "devaddr_list": []
            }
        }
            
        '''

        downland_remote_files(parse_msg["data"]["file_url"], "xx.bin")

        logger.info(f'downland file: {parse_msg["data"]["file_url"]}')

        for devaddr in parse_msg["data"]["devaddr_list"]:

            UpdateWebSocketClient(f"ws://{NS_HOST}/ws/uplink/{devaddr}").connect()


client = mqtt.Client()

# 指定回调函数
client.on_connect = on_connect
client.on_message = on_message

# 建立连接
client.connect('broker.emqx.io', 1883, 60)
# 发布消息
client.publish('lora1',payload='Hello World',qos=0)

client.loop_forever()

